//
//  AiCustomUtils.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/11/2.
//

import Foundation

//type 类型IAiModelType
class AiCustomUtils :BaseViewModel {
    static let shared = AiCustomUtils()
    private var aiModel: [String: AiCustomBean]=[:]
    
    private func log(_ msg: String) {
        showLog("aiCustom", msg)
    }
    
    //app启动跟，进入设置页面需要加载一次
    func doCustomAi() {
        request(isLoading: false) {
            self.log("数据转换，以及添加临时数据")
            try await self.doConvert()
            try await self.addTemBean(type: IAiModelType.diaryReply.rawValue)
            try await self.addTemBean(type: IAiModelType.chat.rawValue)
            try await self.addTemBean(type: IAiModelType.chat2.rawValue)
            try await self.addTemBean(type: IAiModelType.comment.rawValue)
            try await self.addTemBean(type: IAiModelType.aiDiary.rawValue)
            try await self.addTemBean(type: IAiModelType.call.rawValue)
            try await self.addTemBean(type: IAiModelType.weeklyLetter.rawValue)
            try await self.addTemBean(type: IAiModelType.image.rawValue)
            try await self.addTemBean(type: IAiModelType.memory.rawValue)
            return true
        } suc: { _ in
        } fail: {_ in
        }
    }
    
    //旧数据执行转换,130开始
    private func doConvert() async throws {
        try await self.doConvert2(type: IAiModelType.diaryReply.rawValue)
        try await self.doConvert2(type: IAiModelType.chat.rawValue)
        try await self.doConvert2(type: IAiModelType.chat2.rawValue)
        try await self.doConvert2(type: IAiModelType.comment.rawValue)
        try await self.doConvert2(type: IAiModelType.aiDiary.rawValue)
        try await self.doConvert2(type: IAiModelType.call.rawValue)
        try await self.doConvert2(type: IAiModelType.weeklyLetter.rawValue)
        try await self.doConvert2(type: IAiModelType.image.rawValue)
        try await self.doConvert2(type: IAiModelType.memory.rawValue)
    }
    
    //旧数据直接转换
    private func doConvert2(type: String) async throws {
        if let old = AiManager.shared.getAiCustom2(key: type) {
            log("执行转换：\(type)")
            let dao = AiCustomDao()
            var existBean = try await dao.get(host: old.host ?? "", model: old.model ?? "", token: old.token ?? "")
            //不存在才能添加
            if (existBean == nil) {
                let bean = AiCustomBean()
                bean.objectId = UUID().uuidString
                bean.name = old.model
                bean.host = old.host
                bean.token = old.token
                bean.model = old.model
                bean.active = true
                bean.temperature = configManager.getConfig().AiConfig.temperature ?? 0.9
                bean.top_p = configManager.getConfig().AiConfig.top_p ?? 0.95
                try await dao.insert(bean: bean)
                existBean = bean
            }
            addAiCustomMode(type: type, value: existBean?.objectId ?? "")
            //删除旧的
            DispatchQueue.main.async {
                if var oldMap = AiManager.shared.getAiCustom() {
                    oldMap.removeValue(forKey: type)
                    AppStorageManager.shared.aiCustom = toJson(dict: oldMap)
                }
            }
        }
    }
    
    //添加临时数据，方便快速访问
    private func addTemBean(type: String) async throws {
        try await addTemBean(type: type, bean: getAiCustomBean(type: type))
    }
    
    //添加临时数据，方便快速访问
    func addTemBean(type: String, bean: AiCustomBean?) {
        if (bean != nil) {
            aiModel[type] = bean
        } else {
            aiModel.removeValue(forKey: type)
        }
    }
    
    private func getAiCustomBean(type: String) async throws -> AiCustomBean? {
        let map = try? fromJson(AppStorageManager.shared.aiCustom2,  [String:String].self)
        guard let id = map?[type] else {
            return nil
        }
        let bean = try await AiCustomDao().get(objectId: id)
        return bean
        
    }
    
    func getCustomStatus(type: String)-> String {
        if (isCustomAi(type: type)) {
            return "已配置"
        }
        return "未配置"
    }
    
    func isVisibility(type: String, objectId: String) -> Bool {
        return aiModel[type]?.objectId == objectId
    }
    
    func isCustomAi(type: String)-> Bool {
        return getCustomHost(type: type).isEmpty == false
        && getCustomToken(type: type).isEmpty == false
        && getCustomModel(type: type).isEmpty == false
    }
    
    func getCustomHost(type: String)-> String {
        return getCustomBean(type: type)?.host ?? ""
    }
    
    func getCustomToken(type: String)-> String {
        return getCustomBean(type: type)?.token ?? ""
    }
    
    func getCustomModel(type: String)-> String {
        return getCustomBean(type: type)?.model ?? ""
    }
    
    func getCustomBean(type: String)-> AiCustomBean? {
        return aiModel[type]
    }
    
    //添加错误信息
    func reportError(errorId: String, typeName: String, content: String, custom: AiCustomBean) {
        request(isLoading: false) {
            let dao = AiCustomErrorDao()
            let bean = AiCustomErrorBean()
            bean.objectId = UUID().uuidString
            bean.id = errorId
            bean.name = typeName
            bean.host = custom.host
            bean.model = custom.model
            bean.token = custom.token
            bean.time = getMillisecond(getNetTimeLocal())
            bean.content = content
            try await dao.insert(bean: bean)
            return true
        } suc: { _ in
            self.log("错误信息提交成功")
        } fail: {
            self.log("错误信息提交失败：\($0.message)")
        }
    }
    
    //选中类型
    func addAiCustomMode(type: String, value: String) {
        DispatchQueue.main.async {
            var map = (try? fromJson(AppStorageManager.shared.aiCustom2,  [String:String].self)) ?? [:]
            map[type] = value
            AppStorageManager.shared.aiCustom2 = toJson(dict: map)
        }
    }
    
    
}
